package com.miracle.flexAPI.coreConfig;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.miracle.flexAPI.api.entity.SysDatasource;
import com.miracle.flexAPI.api.mapper.SysDatasourceMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.ServletContextAware;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

/**
 * todo 正常情况需要打开Component注解
 * 从数据库加载数据源
 * 该方法会在填充完普通Bean的属性，但是还没有进行Bean的初始化之前执行
 */
@Slf4j
//@Component
public class LoadDatasourceConfig implements ServletContextAware {

    @Resource
    private SysDatasourceMapper sysDatasourceDao;

    @Autowired
    DynamicRoutingDataSource dynamicRoutingDataSource;

    @Override
    public void setServletContext(ServletContext servletContext) {
        SysDatasource model = new SysDatasource();
        model.setIsLoad(1);
        List<SysDatasource> list = sysDatasourceDao.queryByDto(model);
        if (list.size() > 0){
            for (SysDatasource data : list) {
                String vcUrl = data.getVcUrl();
                String vcUser = data.getVcUser();
                String vcPwd = data.getVcPwd();
                String vcDriver = data.getVcDriver();
                try {
                    Class.forName(vcDriver);
                    Connection conn = DriverManager.getConnection(vcUrl, vcUser, vcPwd);
                    if(conn != null){
                        DruidDataSource druidDataSource = new DruidDataSource();
                        druidDataSource.setUrl(vcUrl);
                        druidDataSource.setUsername(vcUser);
                        druidDataSource.setPassword(vcPwd);
                        druidDataSource.setDriverClassName(vcDriver);
                        dynamicRoutingDataSource.addDataSource(data.getVcSourceCode(),druidDataSource);
                    }
                } catch (SQLException e) {
                    log.error(String.valueOf(e));
                } catch (ClassNotFoundException e) {
                    log.error(String.valueOf(e));
                }
            }
        }
    }
}
